package stackdemo;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2024-01-17
 * Time: 17:53
 */
class Solution1 {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for(int i = 0; i< s.length(); i++) {
            //1.遍历字符串
            char ch = s.charAt(i);
            //2.左括号压栈
            if(ch == '{' || ch == '(' || ch == '[') {
                stack.push(ch);
            }else {
                //3.1 如果出现右括号而栈为空
                if(stack.empty()) {
                    return false;
                }
                //这里要先peek，以防不匹配造成的数据丢失
                char ch2 = stack.peek();
                //3.2 判断括号是否匹配
                if((ch == '}' && ch2 == '{') || (ch == ')' && ch2 == '(') || (ch == ']' && ch2 == '[')) {
                    stack.pop();
                }else {
                    return false;
                }
            }
        }
        return stack.empty();
    }
}